//
//  QAAppdelegate.m
//  MMVoice
//
//  Created by mac on 2025/3/4.
//


#import <AFNetworking/AFNetworking.h>
#import "QAADHelper.h"
#import "QATool.h"
#import "QAAppDelegate.h"
#import "QALoginServerIDViewController.h"
#import <AFBrowser/AFPlayer.h>
#import <AFBrowser/AFBrowserViewController.h>
#import <AFModule/AFDeviceObserver.h>
#import "QASocketClient.h"
#import "QABaseNavigationController.h"
#import "QATabBarConfig.h"
#import "QACommonUtils.h"
#import <UserNotifications/UserNotifications.h>
#import "QAIMSetUserDefaultTool.h"
#import <IQKeyboardManager/IQKeyboardManager.h>
#import "QAIMDatabase.h"
#import "MOKeepAlivePlayer.h"
#import "QAWindowSafeView.h"
#import "MPLockHelper.h"
#import "QACMMotionManager.h"
#import "QAReceiveMessageManager.h"

@interface QAAppDelegate()<UNUserNotificationCenterDelegate,AFDeviceDelegate>

@property (assign, nonatomic) UIBackgroundTaskIdentifier backIden;
/// 安全模糊保护
@property(nonatomic, strong) QAWindowSafeView *safeView;
///启动YES ， 判断一次是否需要显示应用锁
@property (nonatomic, assign) BOOL isLaunch;

@end

@implementation QAAppDelegate

+ (void)InitQAAppDelegate {
    //开启网络监听
    [self.class netWorkChangeEven];
    
    [QAReceiveMessageManager manager];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.isLaunch = YES;
    QAPro.globalData.appStart = YES;
    [QAPro.globalService initLanguageConfig];
    MWCache.delegate = [QAGlobalManager class];
    
    [[UITextField appearance] setTintColor:[UIColor main_Color]];
    [[UITextView appearance] setTintColor:[UIColor main_Color]];
    
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    if (MWCache.user.isLogin) {
        self.window.rootViewController = [QATabBarConfig configTabbarController];
    } else {
        QALoginServerIDViewController *vc = [[QALoginServerIDViewController alloc] init];
        QABaseNavigationController *navi = [[QABaseNavigationController alloc] initWithRootViewController:vc];
        self.window.rootViewController = navi;
    }
    [self.window makeKeyAndVisible];
    
    //开启网络监听
    [self.class netWorkChangeEven];
    
    //已登录，刷新token
    if(MWCache.user.isLogin){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
            [[QAGlobalManager manager]requestAddressConfigComplete:^{
                [[QAGlobalManager manager]requestLoginByTokenComplete:nil];
            }];
        });
    }
    
    //注册 APNs
    [self registerRemoteNotification];
    
    if ([QACommonUtils checkFirstLaunch]) {
        SETUserDefaults([NSNumber numberWithBool:YES], KEY_NOTICEOFF);
        SETUserDefaults([NSNumber numberWithBool:YES], KEY_SOUNDOFF);
        SETUserDefaults([NSNumber numberWithBool:YES], KEY_SHARKOFF);
        SETUserDefaults([NSNumber numberWithBool:YES], KEY_MSG_VOICE_PLAYBACK);//默认扬声器播放
        SETUserDefaults(@"0", @"clickAllSelect");//是否点击全选
    }
    
    [QAReceiveMessageManager manager];
    
    //初始化字体
    [self configMessageFont];
    
    //IQKeyboard
    [self configIQKeyboard];
    
    if (MWCache.customDarkModel) {
        BOOL isDark = MWCache.isDark;
        [UIApplication sharedApplication].keyWindow.overrideUserInterfaceStyle = isDark ? UIUserInterfaceStyleDark : UIUserInterfaceStyleLight;
        [UIApplication sharedApplication].keyWindow.rootViewController.overrideUserInterfaceStyle = isDark ? UIUserInterfaceStyleDark : UIUserInterfaceStyleLight;
    }else{
        [UIApplication sharedApplication].keyWindow.overrideUserInterfaceStyle = UIUserInterfaceStyleUnspecified;
        [UIApplication sharedApplication].keyWindow.rootViewController.overrideUserInterfaceStyle = UIUserInterfaceStyleUnspecified;
    }
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    [MOXLogUntil LogNomalWithString:@"application---WillResignActive"];
    MWCache.resignActiveTime = @([QAGlobalManager manager].getNowServerTime);
    
    if (MWCache.user.isLogin) {
        MWCache.appBadgeCount = [[QAIMDatabase sharedInstance] getAllUnreadCount];
        [UIApplication sharedApplication].applicationIconBadgeNumber = MWCache.appBadgeCount;
        [QAModuleService mwSetBadge:MWCache.appBadgeCount];
    } else {
        [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
        [QAModuleService mwSetBadge:0];
    }
    [AFPlayer pauseAllPlayer];
    if (!QATool.isBusy) {///会影响语音消息播放
        if (![[self topViewControllerForKeyWindow] isKindOfClass:NSClassFromString(@"QAChatViewController")]) {
            [AVAudioSession.sharedInstance setCategory:AVAudioSessionCategoryAmbient withOptions:(AVAudioSessionCategoryOptionMixWithOthers) error:nil];
            [[AVAudioSession sharedInstance] setActive:NO withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];
        }
    }
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    //IDFA权限
    [QAADHelper checkAdTrackingEnableComplete:nil];
    if (!QATool.isBusy) {
        if (AVAudioSession.sharedInstance.otherAudioPlaying && [[NSObject topViewControllerForKeyWindow] isKindOfClass:AFBrowserViewController.class]) {
            [AVAudioSession.sharedInstance setCategory:AVAudioSessionCategorySoloAmbient error:nil];
            [AVAudioSession.sharedInstance setCategory:AVAudioSessionCategoryPlayback error:nil];
            [AVAudioSession.sharedInstance setActive:YES error:nil];
        } else {
            [AVAudioSession.sharedInstance setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];
            [AVAudioSession.sharedInstance setActive:YES error:nil];
        }
        [AFPlayer resumeAllPlayer];
    }

    [MOXLogUntil LogNomalWithString:@"application---DidBecomeActive"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"applicationDidBecomeActive" object:nil userInfo:nil];
    if (self.isLaunch) {
        [AFDeviceObserver addCallObserver:self];
        self.isLaunch = NO;
        MWCache.resignActiveTime = @([QAGlobalManager manager].getNowServerTime - MWCache.resignActiveTime.doubleValue);
        [self doLock];
    }
    if (MWCache.user.isLogin && [MWCache.netStatus integerValue] != 0) {
        if (!QASocketClient.msgSocket.isConnected) {
            [MOXLogUntil LogNomalWithString:@"  ----- ----- ----- applicationDidBecomeActive loginByTokenDc"];
            [[QAGlobalManager manager]requestLoginByTokenComplete:nil];
        }
    }
    [self.class deleteLocalPush];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [MOKeepAlivePlayer applicationWillEnterForeground];
    
    [MOXLogUntil LogNomalWithString:@"application---WillEnterForeground"];
    [[NSNotificationCenter defaultCenter] postNotificationName:MPKey_Network_StatusChanged object:MWCache.netStatus];
    if ([MWCache.safeWindowOpen integerValue] == 1) {
        [self.safeView hide];
        self.safeView = nil;
    }
    [self doLock];
    if (MWCache.user.isLogin) {
        NSString *shakeLock = [NSString stringWithFormat:@"%@_sl",MWCache.user.userId];
        BOOL isShake = [MPLockHelper coreArchiveBoolforKey:shakeLock];
        if (isShake) {
            [[QACMMotionManager shareInstance]startAccelerometer];
        }
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationSignificantTimeChangeNotification object:nil];
    [self endBack];
}

- (void)applicationProtectedDataWillBecomeUnavailable:(UIApplication *)application {
    SETUserDefaults(@(1), @"Lock_Screen");
    NSLog(@"锁屏");
}

- (void)applicationDidEnterBackground:(UIApplication *)application {

    [MOXLogUntil LogNomalWithString:@"application---DidEnterBackground"];

    [[NSNotificationCenter defaultCenter] postNotificationName:Application_Did_Enter_Background object:nil];

    if ([self didUserPressLockButton]) {
        NSLog(@" -------------------------锁屏------------------------- ");
        SETUserDefaults(@(1), @"Lock_Screen");
    } else {
        NSLog(@" -------------------------Home------------------------- ");
        MWCache.resignActiveTime = @([QAGlobalManager manager].getNowServerTime);
    }
    
    [QAPro.offlineService loadMsgOnFree];
    if ([MWCache.safeWindowOpen integerValue] == 1) {
        self.safeView.hidden = NO;
    }

    WeakSelf(ws);
    [MOKeepAlivePlayer applicationDidEnterBackground];
    _backIden = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if(weakSelf.backIden != UIBackgroundTaskInvalid) {
                weakSelf.backIden = UIBackgroundTaskInvalid;
            }
        });

        if (QAPro.globalData.isReciveOffLineMsg == NO) {
            [QAPro.offlineService loadMsgOnFree];
        }
        NSLog(@"DidEnterBackground endback -----_backIden  = %ld",weakSelf.backIden);
        if (MWCache.user.isLogin) {
            [QASocketClient disconnect];
            [QAModuleService mwSetBadge:MWCache.appBadgeCount];
        }
        [self endBack];

    }];

}

- (void)applicationWillTerminate:(UIApplication *)application {
    [MOXLogUntil LogNomalWithString:@"application---WillTerminate"];
    MWCache.resignActiveTime = @([QAGlobalManager manager].getNowServerTime);
    [[QACMMotionManager shareInstance]startAccelerometer];
    [MOXLogUntil appenderClose];

    if (MWCache.user.isLogin) {
        WeakSelf(ws);
        _backIden = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
            dispatch_async(dispatch_get_main_queue(), ^{
                if(weakSelf.backIden != UIBackgroundTaskInvalid) {
                    weakSelf.backIden = UIBackgroundTaskInvalid;
                }
            });
            [QAModuleService mwSetBadge:MWCache.appBadgeCount];
        }];
    }
}

- (void)endBack {
    NSLog(@"end=============");
    NSLog(@"[UIApplication sharedApplication].backgroundTimeRemaining == %f   ------ _backIden : %ld",[UIApplication sharedApplication].backgroundTimeRemaining,_backIden);
    [[UIApplication sharedApplication] endBackgroundTask:_backIden];
    _backIden = UIBackgroundTaskInvalid;
}

/// MARK: 应用锁
- (void)doLock {
    NSInteger lockTime = [MWCache.lockTime integerValue];
    double now = [QAGlobalManager manager].getNowServerTime;
    NSLog(@"---- 计算时间：%g ---", now - MWCache.resignActiveTime.doubleValue);
    NSLog(@"---- 锁屏时间:%ld -----", lockTime);
    if (now - MWCache.resignActiveTime.doubleValue > (lockTime * 1000)) {
        [MPLockHelper judgeShowLockViewWithDoNotCareShake:YES showShake:NO];
    };
}

- (BOOL)didUserPressLockButton {
    //获取屏幕亮度
    CGFloat oldBrightness = [UIScreen mainScreen].brightness;
    //以较小的数量改变屏幕亮度
    [UIScreen mainScreen].brightness = oldBrightness + (oldBrightness <= 0.01 ? (0.01) : (-0.01));
    CGFloat newBrightness = [UIScreen mainScreen].brightness;
    //恢复屏幕亮度
    [UIScreen mainScreen].brightness = oldBrightness;
    //判断屏幕亮度是否能够被改变
    return oldBrightness != newBrightness;
}

+ (void)netWorkChangeEven {
   [[AFNetworkReachabilityManager sharedManager] startMonitoring];
   [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
       switch (status) {
           case -1:
               [MOXLogUntil LogNetChangeWithString:@"未知网络"];
               break;
           case 0:
               [MOXLogUntil LogNetChangeWithString:@"网络不可达"];
               break;
           case 1:
               [MOXLogUntil LogNetChangeWithString:@"WWAN网络"];
               break;
           case 2:
               [MOXLogUntil LogNetChangeWithString:@"wifi网络"];
               break;
           default:
               break;
       }
       
       if (status == AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi) {
           [MOXLogUntil LogNetChangeWithString:@"有网"];
           MWCache.hasNet = YES;
           MWCache.netStatus = @1;
           MWCache.gsFailTimes = 0;

       } else {
           [MOXLogUntil LogNetChangeWithString:@"没有网"];
           MWCache.hasNet = NO;
           MWCache.netStatus = @0;
       }
       [[NSNotificationCenter defaultCenter] postNotificationName:@"af_netWorkChange" object:@(status)];
       [[NSNotificationCenter defaultCenter] postNotificationName:MPKey_Network_StatusChanged object:@(MWCache.hasNet)];
   }];
}

/** 注册 APNs */
- (void)registerRemoteNotification {
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionCarPlay) completionHandler:^(BOOL granted, NSError *_Nullable error) {
        if (!error) {
            NSLog(@"request authorization succeeded!");
            dispatch_async(dispatch_get_main_queue(), ^{
                [[UIApplication sharedApplication] registerForRemoteNotifications];
            });
        } else {
            NSLog(@"request authorization failed!");
        }
    }];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    if (![deviceToken isKindOfClass:[NSData class]]) return;
    const unsigned *tokenBytes = (const unsigned *)[deviceToken bytes];
    NSString *hexToken = [NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x",
                ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),
                ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),
                ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];
    [MOXLogUntil LogNomalWithString:@"deviceToken : %@",hexToken];
    
    if (hexToken.length > 0) {
        MWCache.deviceToken = hexToken;
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [QAModuleService updateVersionOrTokenToServerWithNowDeviceToken:hexToken];
        });
    }
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler API_AVAILABLE(ios(10.0)) {
    NSDictionary * userInfo = notification.request.content.userInfo;
    NSLog(@"userInfo = %@",userInfo);
    //当应用处于前台时提示设置，需要哪个可以设置哪一个
    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
}

// 关闭本地推送
+ (void)deleteLocalPush {
    // 获取所有本地通知数组
    if (![UIApplication sharedApplication].scheduledLocalNotifications) {
        return;
    }
    
    NSArray *localNotifications = [UIApplication sharedApplication].scheduledLocalNotifications;
    
    if (localNotifications) {
        for (UILocalNotification *notification in localNotifications) {
            NSDictionary *userInfo = notification.userInfo;
            if (userInfo) {
                // 根据设置通知参数时指定的key来获取通知参数
                NSString *info = userInfo[@"name"];
                
                // 如果找到需要取消的通知，则取消
                if ([info isEqualToString:@"loaclPushOne"]) {
                    if (notification) {
                        [[UIApplication sharedApplication] cancelLocalNotification:notification];
                    }
                    break;
                }
            }
        }
    }
}

#pragma mark - 设置主要聊天字号大小
- (void)configMessageFont {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSInteger fontLevel = [QASetUserDefaultTool getFontSizeCoefficient];
        switch (fontLevel) {
            case 1:
                [QAPro globalData].sysMessageFont = [UIFont systemFontOfSize:11.0];
                [QAPro globalData].messageFont = [UIFont systemFontOfSize:14.0];
                break;
            case 2:
                [QAPro globalData].sysMessageFont = [UIFont systemFontOfSize:14.0];
                [QAPro globalData].messageFont = [UIFont systemFontOfSize:16.0];
                break;
            case 3:
                [QAPro globalData].sysMessageFont = [UIFont systemFontOfSize:15.0];
                [QAPro globalData].messageFont = [UIFont systemFontOfSize:18.0];
                break;
            case 4:
                [QAPro globalData].sysMessageFont = [UIFont systemFontOfSize:17.0];
                [QAPro globalData].messageFont = [UIFont systemFontOfSize:20.0];
                break;
            default:
                [QAPro globalData].sysMessageFont = [UIFont systemFontOfSize:14.0];
                [QAPro globalData].messageFont = [UIFont systemFontOfSize:16.0];
                break;
        }
    });
}

- (void)configIQKeyboard {
    IQKeyboardManager *keyboardManager = [IQKeyboardManager sharedManager]; // 获取类库的单例变量
    [[keyboardManager disabledDistanceHandlingClasses] addObject:NSClassFromString(@"QAChatViewController")];
    
    // 控制整个功能是否启用
    keyboardManager.enable = YES;
    // 控制点击背景是否收起键盘
    keyboardManager.shouldResignOnTouchOutside = YES;
    // 控制键盘上的工具条文字颜色是否用户自定义
    keyboardManager.shouldToolbarUsesTextFieldTintColor = YES;
    // 有多个输入框时，可以通过点击Toolbar 上的“前一个”“后一个”按钮来实现移动到不同的输入框
    keyboardManager.toolbarManageBehaviour = IQAutoToolbarBySubviews;
    // 控制是否显示键盘上的工具条
    keyboardManager.enableAutoToolbar = YES;
    // 是否显示占位文字
    keyboardManager.shouldShowToolbarPlaceholder = YES;
    // 设置占位文字的字体
    keyboardManager.placeholderFont = [UIFont boldSystemFontOfSize:16];
    // 输入框距离键盘的距离
    keyboardManager.keyboardDistanceFromTextField = 10.0f;
    
}

- (QAWindowSafeView *)safeView{
    if (!_safeView) {
        _safeView = [[QAWindowSafeView alloc]init];
    }
    return _safeView;
}

@end
